package com.pat.web.controller;

import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.NoNeedLogon;
import com.pat.web.model.PetWelfare;
import com.pat.web.model.PetWelfareCategory;
import com.pat.web.model.Welfare;

public class WelfareController extends Controller{
	private static final int PAGESIZE = 20;

	@NoNeedLogon
	public void getWelfareList(){
		Long userid = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		List<Record> records = Db.find("select id,user_id,type,title,introduction,deadline,detail_id,create_time,pet_welfare_id from welfare where user_id = ?  and  "
				+ "type = ? ", userid,  getParaToInt("type"));
		response.setData(records);
		render(new JsonRender(response));
	}
	
	@NoNeedLogon
	public void  getWelfareDetailById(){
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		Record record = Db.findFirst("select wd.id,wd.title,w.welfare_card_number,wd.use_instructions,wd.expiration_date,wd.create_time,wd.image_url,wd.period_validity from welfare_detail wd,welfare w where w.id =? and w.detail_id = wd.id and w.user_id = ?", getParaToInt("id"),getAttr(Constants.LOGIN_USER_ID));
		response.setData(record);
		render(new JsonRender(response));
	}
	
	@NoNeedLogon
	public void getPetWelfareList(){
		Integer pageIndex = getParaToInt("pageIndex");
		if (pageIndex == null || pageIndex < 1) {
			pageIndex = 1;
		}
		Integer pageSize = getParaToInt("pageSize");
		if (pageSize == null) {
			pageSize = PAGESIZE;
		}
		
		Integer type = getParaToInt("type");
		String joinsql = " left join ";
		if (type != null && type == 1) {
			joinsql = " inner join ";
		}
		
		Long userid = getAttr(Constants.LOGIN_USER_ID);;
		String selectSql = null;
		String sqlExceptSelect = null;
		if (userid != null) {
			selectSql = "select pwf.id,pwf.name,pwf.address,pwf.deadline,pwf.collection_num,pwf.background_image_url,pwf.county_id,pwf.category_id, wf.pet_welfare_id ";
			sqlExceptSelect ="from pet_welfare pwf " +  joinsql  + " welfare wf on wf.pet_welfare_id = pwf.id and wf.user_id = ? and wf.type = 2 where 1=1 ";
		}else{
			selectSql = "select pwf.id,pwf.name,pwf.address,pwf.deadline,pwf.collection_num,pwf.background_image_url,pwf.county_id,pwf.category_id ";
			sqlExceptSelect ="from pet_welfare pwf  where 1=1 ";
		}
		Integer categoryId  = getParaToInt("categoryId");
		Integer countyId  = getParaToInt("countyId");
		Integer cityId  = getParaToInt("cityId");
		Integer provinceId  = getParaToInt("provinceId");
		
		if(categoryId != null){
			sqlExceptSelect = sqlExceptSelect + "and category_id = " + categoryId;
		}
		
		if(countyId != null){
			sqlExceptSelect = sqlExceptSelect + " and county_id = " + countyId;
		}
		
		if(cityId != null){
			sqlExceptSelect = sqlExceptSelect + " and city_id = " + cityId;
		}
		
		if(provinceId != null){
			sqlExceptSelect = sqlExceptSelect + " and province_id = " + provinceId;
		}
		
		sqlExceptSelect = sqlExceptSelect + " order by pwf.create_time desc";
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		
		Page<Record> records =  null;
		if (userid != null) {
			records =  Db.paginate(pageIndex, pageSize,selectSql,sqlExceptSelect,userid);
		}else{
			records =  Db.paginate(pageIndex, pageSize,selectSql,sqlExceptSelect);
		}
		
		response.setData(records);
		render(new JsonRender(response));
	}
	
	//收藏养宠福利
	public void focusPetWelfare(){
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		Integer operateType = getParaToInt("operateType");
		Long petWelfareId =  getParaToLong("petWelfareId");
		Welfare welfare = Welfare.dao.findFirst("select id,user_id,type,title,introduction,deadline,detail_id,create_time,pet_welfare_id from welfare where user_id = ?  and "
				+ "pet_welfare_id = ? and  type = 2 ", userId,getParaToInt("petWelfareId"));
		
		ApiResponse response = new ApiResponse();
		if (welfare != null) {
			if(operateType != null && operateType == 1){
				response.setStatusCode("00001");
				response.setErrorMessage("该福利已经收藏过了");
			}else{
				if(welfare.delete()){
					PetWelfare petWelfare = PetWelfare.dao.findById(petWelfareId);
					if (petWelfare != null) {
						petWelfare.setCollectionNum(petWelfare.getCollectionNum() - 1);
						petWelfare.setUpdateTime(new Date());
						petWelfare.update();	
						response.setStatusCode("0000");
						response.setData(petWelfare.getCollectionNum());
					}
				}else{
					response.setStatusCode("00003");
					response.setErrorMessage("取消收藏失败 ");
				}
			}
			
		}else{
			if(operateType != null && operateType == 1){
				Record record = Db.findFirst("select pwf.id,pwf.name,pwf.address,pwf.deadline,pwf.collection_num, "
						+ "pwf.background_image_url,pwf.county_id,pwf.category_id,pwf.introduction,pwf.detail_id,pwf.title, "
						+ " wd.active_content,wd.notice "
						+ "from pet_welfare pwf,welfare_detail wd where pwf.detail_id = wd.id and pwf.status = 1 and pwf.id = ? ", petWelfareId);
				if (record != null) {
					welfare = new Welfare();
					welfare.setCreateTime(new Date());
					welfare.setDeadline(record.getDate("deadline"));
					welfare.setDetailId(record.getLong("detail_id"));
					welfare.setIntroduction(record.getStr("introduction"));
					welfare.setPetWelfareId(record.getLong("id"));
					welfare.setTitle(record.getStr("title"));
					welfare.setType(2);
					welfare.setUserId(userId);
					
					if(welfare.save()){
						PetWelfare petWelfare = PetWelfare.dao.findById(petWelfareId);
						if (petWelfare != null) {
							petWelfare.setCollectionNum(petWelfare.getCollectionNum() + 1);
							petWelfare.setUpdateTime(new Date());
							petWelfare.update();	
							response.setStatusCode("0000");
							response.setData(petWelfare.getCollectionNum());

						}
					}else{
						response.setStatusCode("00002");
						response.setErrorMessage("收藏失败 ");
					}
					
				}else{
					response.setStatusCode("00002");
					response.setErrorMessage("收藏失败 ");
				}
			}else{
				response.setStatusCode("00004");
				response.setErrorMessage("取消收藏失败 ");
			}
		}
		
		render(new JsonRender(response));
	}
	
	@NoNeedLogon
	public void getPetWelfareDetail(){
	
		Record record = Db.findFirst("select pwf.id,pwf.name,pwf.address,pwf.deadline,pwf.collection_num,pwf.background_image_url,pwf.county_id,pwf.category_id, wd.active_content,wd.notice, "
				+ " (select wf.pet_welfare_id  from  welfare wf  where  wf.pet_welfare_id = ? and wf.user_id = ? and wf.type = 2 )  pet_welfare_id "
				+ "from pet_welfare pwf,welfare_detail wd where pwf.detail_id = wd.id and pwf.status = 1 and pwf.id = ? ", getParaToInt("id"),getAttr(Constants.LOGIN_USER_ID),getParaToInt("id"));
		
		List<Record> records = Db.find("select u.photo from user u ,welfare wl where u.photo is not null and u.id = wl.user_id and wl.type =2 and wl.pet_welfare_id = ?", getParaToInt("id"));
		if(record != null){
			record.set("photos", records);
		}
		
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		
		response.setData(record);
		render(new JsonRender(response));
	}
	
	
	//领取福利
	public void fetchWelfare() {
		Long userid = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();


		PetWelfare petWelfare  = PetWelfare.dao.findFirst("select pwf.id,pwf.name,pwf.address,pwf.deadline,pwf.collection_num,pwf.background_image_url,pwf.detail_id,"
				+ "pwf.county_id,pwf.category_id,pwf.total_number,pwf.left_num,pwf.introduction,pwf.title,wf.user_id "
				+ " from pet_welfare pwf left join welfare wf on wf.pet_welfare_id = pwf.id and wf.user_id = ? and wf.type = 1 "
				+ " where pwf.status = 1  and pwf.id = ? ",userid,getParaToInt("id"));
		
		if(petWelfare != null){
			if(petWelfare.getLong("user_id") != null){
				response.setErrorMessage("用户已经领取过该福利");
				response.setStatusCode("00001");
				renderJson(response);
				return;
			}
			
			if(petWelfare.getLong("left_num") != null && petWelfare.getLong("left_num") == 0){
				response.setStatusCode("00002");
				response.setErrorMessage("本轮福利已发放完毕");
				renderJson(response);
				return;
			}
		}
		
		//先更新剩余福利数量
		petWelfare.setLeftNum(petWelfare.getLeftNum() - 1);
		if (petWelfare.update()) {
			Welfare welfare = new Welfare();
			welfare.setCreateTime(new Date());
			welfare.setIntroduction(petWelfare.getIntroduction());
			welfare.setDeadline(petWelfare.getDeadline());
			welfare.setDetailId(petWelfare.getDetailId());
			welfare.setPetWelfareId(petWelfare.getId());
			welfare.setTitle(petWelfare.getTitle());
			welfare.setType(1);
			welfare.setUserId(userid);
			welfare.setWelfareCardNumber(Long.toHexString(petWelfare.getId()).toUpperCase() + userid);//TODO  如何生成
			welfare.save();
			response.setData("领取成功");
			response.setStatusCode("0000");
			renderJson(response);
		}		
	}
	
	@NoNeedLogon
	public void getPetWelfareCategory(){
		List<PetWelfareCategory>petWelfareCategories = PetWelfareCategory.dao.find("select * from  pet_welfare_category");
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		
		response.setData(petWelfareCategories);
		render(new JsonRender(response));
	}
	
}
